<template>
  <continer class="call-continer" :shadow="!isCustom">
    <template slot="search">
      <slot name = 'search'></slot>
      <QuickSearch
        v-if="!isCustom"
        :advForm="quickSearchForm"
        @QuickSearch="getCallList"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <slot name = 'oprate'></slot>
      <customSearch
        v-if="!isCustom"
        ref="customSearch"
        class="customSearch"
        :fieldList="fieldList"
        :fieldSelectList="fieldSelectList"
        :customList="customList"
        :conditionList="conditionList"
        @deleteCustomClick="deleteCustomClick"
        @popverShow="popverShow"
        @saveCondition="saveConditionFun"
        @handleSearch="handleSearch"
      ></customSearch>
      <el-button type="primary" @click="pageChange(1)" v-if="!isCustom">刷新</el-button>
    </template>
    <template slot="content">
      <callTable
        v-if="isShowTabel"
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        v-loading="showLoading"
        :headersConfig="true"
        ref="callTabelRef"
        :selection="true"
        :batchs="configBatchs"
        @batchClick="batchClick"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              :show-overflow-tooltip="item.width > 0"
              align="left"
              v-if="
                item.show &&
                item.prop !== 'oprate' &&
                item.prop !== 'customerNumber' &&
                item.prop !== 'callType' &&
                item.prop !== 'status' &&
                item.prop !== 'bridgeDuration' &&
                item.prop !== 'customerCountry' &&
                item.prop !== 'displayNumberArea' &&
                item.prop !== 'agentRingDuration' &&
                item.prop !== 'customerRingDuration' &&
                item.prop !== 'hangUpSide' &&
                item.prop !== 'failureReason' &&
                item.prop !== 'satisfyDuration' &&
                item.prop !== 'customerName' &&
                item.prop !== 'recordFileUrl' &&
                item.prop !== 'voiceMailUrl'  &&
                item.prop !== 'tags' &&
                item.prop !== 'department' &&
                item.prop !== 'transferAgent' &&
                item.prop !== 'keys'
              "
            >
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'satisfyDuration'"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.satisfyDuration | getTimeLength }}</span>
              </template>
            </u-table-column>
            <u-table-column :prop='item.prop'
              :label="item.label"
              :key="item.label + index"
              v-if="item.show && item.prop === 'tags'"
              min-width='200'
            >
              <template slot-scope="scope">
                <el-tooltip placement="top" v-if="scope.row.tags.length">
                  <div slot="content">
                    <tag v-for="(item, index) of scope.row.tags" :key="index" :closeShow="false" :data='tagMap.get(item)'></tag>
                  </div>
                  <tag v-if="scope.row.tags.length" :tagin="true" :closeShow="false" :data='tagMap.get(scope.row.tags[0])'></tag>
                </el-tooltip>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'bridgeDuration'"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.bridgeDuration | getTimeLength }}</span>
              </template>
            </u-table-column>

            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'agentRingDuration'"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.agentRingDuration | getTimeLength }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'customerRingDuration'"
            >
              <template slot-scope="scope">
                <span>{{
                  scope.row.customerRingDuration | getTimeLength
                }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'hangUpSide'"
            >
              <template slot-scope="scope">
                <span class="customerNumber">{{
                  scope.row.hangUpSide | getHangUpSide
                }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'failureReason'"
            >
              <template slot-scope="scope">
                <span class="customerNumber">{{
                  scope.row.failureReason | getFailureReason
                }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              align="left"
              v-if="item.show && item.prop === 'callType'"
            >
              <template slot-scope="scope">
                <span class="customerNumber">{{
                  scope.row.callType | getCallType
                }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              v-if="item.show && item.prop === 'status'"
              align="left"
            >
              <template slot-scope="scope">
                <span class="status">
                  <i
                    class="V7_iconfont V7_iconV7tubiao_dian status"
                    :class="['ANSWER', 'CALL_TRANSFER', 'CALL_CONSULT', 'CALL_CONSULT_TRANSFER', 'CALL_THREEWAY'].indexOf(scope.row.status) > -1?'enable':''"
                  ></i
                  >{{ scope.row.status | getCallStatus }}</span
                >
              </template>
            </u-table-column>
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :min-width="item.width > 0 ? item.width : ''"
              v-if="item.show && item.prop === 'customerNumber'"
              align="left"
            >
              <template slot-scope="scope">
                <span class="customerNumber">{{ scope.row.extraNumber ? scope.row.customerNumber + '-' + scope.row.extraNumber : scope.row.customerNumber | getHideTel}}</span >
                <i
                  class="V7_iconfont V7_iconV7tubiao_tonghua pointer"
                  v-show="visibleDialout"
                  @click="dialoutClick(scope.row.customerNumber, scope.row.extraNumber)"
                ></i>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'recordFileUrl'"
            >
              <template slot-scope="scope">
                <AudioProgress
                  :row="{
                    audioDuration: scope.row.recordingDuration,
                    _id: 'recordFileUrl' + scope.row._id
                  }"
                  v-show="scope.row[item.prop]"
                  :showDowload="
                    limitArr.indexOf('download') > -1 &&
                    limitArr.indexOf('audition') > -1
                  "
                  :showListen="limitArr.indexOf('audition') > -1"
                  :url="scope.row.doubleTrackFileUrl || scope.row.recordFileUrl | getFileUrl"
                  :propIsplay="scope.row.isPlay"
                  @audioClick="restTablePlay"
                ></AudioProgress>
              </template>
            </u-table-column>
                     <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'voiceMailUrl'"
            >
              <template slot-scope="scope">
                <AudioProgress
                  :row="{
                    audioDuration: scope.row.voiceMailDuration,
                    _id: 'voiceMailUrl'+ scope.row._id
                  }"
                  v-show="scope.row[item.prop]"
                  :showDowload="
                    limitArr.indexOf('download') > -1 &&
                    limitArr.indexOf('audition') > -1
                  "
                  :showListen="limitArr.indexOf('audition') > -1"
                  :url="scope.row[item.prop] | getFileUrl"
                  :propIsplay="scope.row.isPlay"
                  @audioClick="restTablePlay"
                ></AudioProgress>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'customerName'"
            >
              <template slot-scope="scope">
                {{ scope.row | getCustName }}
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'customerCountry'"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.customerCountryCode === '86'">
                  {{ scope.row.customerProvince }}-{{ scope.row.customerCity }}
                </span>
                <span v-else>{{scope.row.customerCountry}}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'keys'"
            >
              <template slot-scope="scope">
                {{ scope.row.keysName }}
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              width="84"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'displayNumberArea'"
            >
              <template slot-scope="scope">
                <span v-show="scope.row.displayNumber">
                  <!-- 有外显号，再匹配外显号地区 -->
                   {{ scope.row.callerProvince }}-{{ scope.row.callerCity }}
                </span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              :min-width="item.width > 0 ? item.width : ''"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'department'"
            >
              <template slot-scope="scope">
                <el-tooltip placement="top">
                  <div slot="content" v-if="scope.row.departmentNames.length && scope.row.departmentNames.length > 0">
                    <span>
                      <!-- 部门名称 -->
                      {{ scope.row.departmentNames.join(';') }}
                    </span>
                  </div>
                  <span>
                    <!-- 部门名称 -->
                    {{ scope.row.departmentNames[0] }}
                  </span>
                </el-tooltip>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              :min-width="item.width > 0 ? item.width : ''"
              :key="index"
              align="left"
              v-if="item.show && item.prop === 'transferAgent'"
            >
              <template slot-scope="scope">
                <span>
                  <!-- 转出座席工号 -->
                   {{ scope.row.transferAgent}}
                </span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'oprate' && item.show"
              :key="item.label + index"
              align="center"
              fixed="right"
              width="50"
            >
              <template slot-scope="scope">
                <span class="oprate-btn" @click="handleDetail(scope.row)"
                  >详情</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </callTable>
      <resizeDrawer
        custom-class="m7-drawer"
        title="详情"
        :drawer="isShowDrawer"
        direction="rtl"
        :modal-append-to-body="false"
        :append-to-body="true"
        ref="drawer"
        :isShowMoreBtn="false"
        @closeDraw="closeDraw"
        :size="700"
        class="call-detail-drawer"
      >
        <template slot="column">
          <div style="position:absolute;width:calc(100% - 48px);height:100%">
            <callSummary ref="callSummaryRef"
            @changeCustomerRelation = 'changeCustomerRelation'
            :moduleType="moduleType"
            :showDowload="limitArr.indexOf('download') > -1 &&limitArr.indexOf('audition') > -1"
            :showListen="limitArr.indexOf('audition') > -1"></callSummary>
          </div>
        </template>
      </resizeDrawer>
      <exportDialog
        ref="exportDialogRef"
        @dialog-save="dialogSave"
      ></exportDialog>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop, Watch } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import callTable from '@/components/configCommon/table.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import AudioProgress from '@/components/audio/AudioProgress.vue'
import customSearch from '@/views/dataCenter/callData/customSearch.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import callSummary from '@/views/call/CallSummaryByCallData.vue'
import exportDialog from '@/components/exportDialog/index.vue'
import { isHasFuncOrMenus, getCallTimeLength, getCallStatusName, getCallTypeName, getFormatDateTime, checkHideTel } from '@/utils/common'
import { CtiModule } from '@/store/modules/cti/index'
import { TagModule } from '@/store/modules/tag'
import tag from '@/components/tag/index.vue'
import { CustomerFields, CustomerCondition, FieldSelect } from './callData'
import resizeDrawer from '@/components/globalTool/resizeDrawer/drawer.vue';
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
@Component({
  name: 'callData',
  components: { callTable, continer, AudioProgress, customSearch, QuickSearch, callSummary, exportDialog, tag, resizeDrawer },
  filters: {
    getHideTel (customerNumber) {
      return checkHideTel(customerNumber)
    },
    getFileUrl (url) {
      return url && url.replace(/(http|https):/ig, '')
    },
    getCallType (type) {
      return getCallTypeName(type)
    },
    getCallStatus (status) {
      return getCallStatusName(status)
    },
    getHangUpSide (code) {
      let label
      switch (code) {
        case 'AGENT':
          label = '座席挂机'
          break;
        case 'CUSTOMER':
          label = '客户挂机'
          break;
        case 'SYSTEM':
          label = '系统挂机'
          break;
      }
      return label
    },
    getFailureReason (code) {
      let label
      switch (code) {
        case 510:
          label = '忙'
          break;
        case 511:
          label = '超时'
          break;
        case 512:
          label = '拒接'
          break;
        case 513:
          label = '空号'
          break;
        case 514:
          label = '关机'
          break;
        case 515:
          label = '暂时无法接听'
          break;
        case 516:
          label = '停机'
          break;
      }
      return label
    },
    getTimeLength (timeLength) {
      return getCallTimeLength(timeLength, false)
    },
    getCustName (data) {
      if (data.customerName) { // 匹配到一个客户
        return data.customerName
      } else if (data.matchResult === '000') { // 未知客户
        return '未知客户'
      } else if (data.matchResult === '010') { // 多个客户
        return '多个客户'
      }
    }
  }
})
export default class CallData extends Vue {
  [x: string]: any

  @Watch('forceCondition')
  private forceConditionChange () {
    this.pageChange(1)
  }

  /**
   * forceCondition 强制条件 从其他模块定制通话数据场景
   */
  @Prop({ default: null }) private forceCondition: any
  /**
   * isCustom 是否自定义通话数据模块
   * 是的话 自定义检索 刷新 用插槽的方式外抛
   * 页面外呼 事件外抛
   */
  @Prop({ default: false }) private isCustom: boolean | undefined

  @Prop({ default: true }) private visibleDialout: boolean | undefined

  @Prop({ default: 'dataCenter' }) private moduleType!: string

  @Ref() private exportDialogRef !: exportDialog
  @Ref() private callTabelRef!: callTable
  private $store: any
  private deaultCustomList = [{
    name: '全部通话记录',
    default: true,
    advanceQuery: [
      []
    ]
  }, {
    name: '我的通话记录',
    default: true,
    advanceQuery: [
      [
        {
          fieldKey: 'agentNumber',
          fieldOperator: 'eq',
          fieldValue: [
            (this as any).$store.state.common.session.user.agentNumber
          ]
        }
      ]
    ]
  }]

  private closeDraw () {
    this.isShowDrawer = false
  }

  private customList: any = []
  private tableCheckedList: any = []
  private conditionList: CustomerCondition = {
    // 等于  不等于 包含  不包含  为空      不为空     大于  大于等于 小于 小于等于 介于  不介于
    // 'eq', 'neq', 'in', 'nin', 'empty', 'nempty', 'gt', 'gte', 'lt', 'lte', 'btn', 'nbtn'
    // 客户号码
    customerNumber: { type: 'string', condition: ['eq'] },
    // 通话ID
    _id: { type: 'string', condition: ['eq'] },
    // 服务号
    trunkNumber: { type: 'string', condition: ['eq'] },
    // 外显号
    displayNumber: { type: 'string', condition: ['eq'] },
    // 虚拟号
    virtualNumber: { type: 'string', condition: ['eq'] },
    // 座席工号
    agentNumber: { type: 'string', condition: ['eq'] },
    // 坐席部门
    departments: { type: 'cascader', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'], props: { value: '_id', label: 'name', children: 'children', multiple: true, emitPath: 'false' } },
    // 转出坐席工号
    transferAgent: { type: 'string', condition: ['eq'] },
    // 通话时长
    bridgeDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    // 呼叫时间
    startTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
    // 满意度调查时长
    joinQeueTime: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    // 座席应答时间
    agentAnswerTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
    // 座席振铃时长
    agentRingDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    // 客户振铃时长
    customerRingDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    // 满意度调查时长
    satisfyDuration: { type: 'number', condition: ['eq', 'gte', 'lte', 'between'] },
    // 客户名称
    customerName: { type: 'string', condition: ['in', 'empty', 'nempty'] },
    // 呼叫类型
    callType: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 呼叫状态
    status: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 技能组名称
    queueName: { type: 'string', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 挂机方
    hangUpSide: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 座席名称
    agentName: { type: 'string', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 客户地区
    customerCountry: { type: 'cascader', condition: ['eq', 'neq', 'empty', 'nempty'], props: { label: 'name', value: 'name' } },
    // 外显号地区
    displayNumberArea: { type: 'cascader', condition: ['eq', 'neq', 'empty', 'nempty'], props: { label: 'name', value: 'name' } },
    // 语音导航名称
    ivrId: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'], props: { label: 'name', value: 'nodeId' } },
    // 挂机时间
    hangupTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
    // 满意度调查
    // keys: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 客户接听时间
    customerAnswerTime: { type: 'date', condition: ['between', 'gte', 'lte'] },
    // 呼叫座席时间
    agentStartTime: { type: 'date', condition: ['eq', 'gte', 'lte', 'between'] },
    // 呼叫失败原因
    failureReason: { type: 'select', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'] },
    // 通话录音
    recordFileUrl: { type: 'select', condition: ['empty', 'nempty'] },
    // 留言录音
    voiceMailUrl: { type: 'select', condition: ['empty', 'nempty'] },
    // 标签
    tags: { type: 'cascader', condition: ['eq', 'neq', 'in', 'nin', 'empty', 'nempty'], props: { value: '_id', label: 'name', children: 'children', multiple: true, emitPath: 'false' } }
  }

  private fieldList: CustomerFields[] = [
    {
      label: '客户号码',
      prop: 'customerNumber'
    },
    {
      label: '座席名称',
      prop: 'agentName'
    },
    {
      label: '呼叫类型',
      prop: 'callType'
    },
    {
      label: '呼叫状态',
      prop: 'status'
    },
    {
      label: '呼叫时间',
      prop: 'startTime'
    },
    {
      label: '通话时长', // 通话结束时间 - 呼叫时间
      prop: 'bridgeDuration'
    },
    {
      label: '通话录音',
      prop: 'recordFileUrl'
    },
    {
      label: '留言录音',
      prop: 'voiceMailUrl'
    },
    // 地区拆分成省市
    {
      label: '客户地区',
      prop: 'customerCountry'
    },
    {
      label: '服务号',
      prop: 'trunkNumber'
    },
    {
      label: '外显号',
      prop: 'displayNumber'
    },
    {
      label: '外显号地区',
      prop: 'displayNumberArea'
    },
    {
      label: '虚拟号',
      prop: 'virtualNumber'
    },
    {
      label: '座席工号',
      prop: 'agentNumber'
    },
    {
      label: '座席部门',
      prop: 'departments'
    },
    {
      label: '转出座席工号',
      prop: 'transferAgent'
    },
    {
      label: '技能组',
      prop: 'queueName'
    },
    {
      label: '语音导航',
      prop: 'ivrId'
    },
    {
      label: '座席振铃时长', // 座席接听应答时间 - 呼叫时间
      prop: 'agentRingDuration'
    },
    {
      label: '座席接听时间', // 座席接听应答时间 - 呼叫时间
      prop: 'agentAnswerTime'
    },
    {
      label: '呼叫座席时间', // 座席接听应答时间 - 呼叫时间
      prop: 'agentStartTime'
    },
    {
      label: '客户振铃时长', // 客户接听应答时间 - 呼叫时间
      prop: 'customerRingDuration'
    },
    {
      label: '客户接听时间',
      prop: 'customerAnswerTime'
    },
    {
      label: '挂机方',
      prop: 'hangUpSide'
    },
    {
      label: '呼叫失败原因',
      prop: 'failureReason'
    },
    // {
    //   label: '满意度调查结果',
    //   prop: 'keys'
    // },
    {
      label: '满意度调查时长', // 满意度结束时间 - 满意度开始时间
      prop: 'satisfyDuration'
    },
    {
      label: '通话记录ID',
      prop: '_id'
    },
    {
      label: '客户名称',
      prop: 'customerName'
    },
    {
      label: '挂机时间',
      prop: 'hangupTime'
    },
    {
      label: '标签',
      prop: 'tags'
    }
  ]

  private fieldSelectList: FieldSelect = {
    status: [
      {
        _id: 'IVR',
        name: 'IVR'
      },
      {
        _id: 'QUEUE_ABANDON',
        name: '排队放弃'
      },
      {
        _id: 'ANSWER',
        name: '已接听'
      },
      {
        _id: 'AGENT_NO_ANSWER',
        name: '座席未接听'
      },
      {
        _id: 'CALL_LIMITE',
        name: '并发限制'
      },
      {
        _id: 'BLACK_LIST',
        name: '黑名单'
      },
      {
        _id: 'CUSTOMER_NO_ANSWER',
        name: '客户未接听'
      },
      {
        _id: 'CALL_TRANSFER',
        name: '呼叫转移'
      },
      {
        _id: 'CALL_CONSULT',
        name: '呼叫咨询'
      },
      {
        _id: 'CALL_CONSULT_TRANSFER',
        name: '咨询转移'
      },
      {
        _id: 'CALL_THREEWAY',
        name: '三方'
      },
      {
        _id: 'VOICEMAIL',
        name: '留言'
      },
      {
        _id: 'RISK',
        name: '风控拦截'
      }
    ],
    callType: [
      { name: '呼入', _id: 'incoming' },
      { name: '外呼', _id: 'dialout' },
      { name: '呼叫转移', _id: 'transfer' },
      { name: '咨询转移', _id: 'consultTransfer' },
      { name: '双向回呼', _id: 'webcall' },
      { name: '预览外呼', _id: 'previewDialout' },
      { name: '自动外呼', _id: 'autoDialout' }
    ],
    failureReason: [
      { name: '忙', _id: 510 },
      { name: '超时', _id: 511 },
      { name: '拒接', _id: 512 },
      { name: '空号', _id: 513 },
      { name: '关机', _id: 514 },
      { name: '暂时无法接听', _id: 515 },
      { name: '停机', _id: 516 }
    ],
    hangUpSide: [
      { name: '座席挂机', _id: 'AGENT' },
      { name: '客户挂机', _id: 'CUSTOMER' },
      { name: '系统挂机', _id: 'SYSTEM' }
    ],
    ivrId: [],
    customerCountry: [],
    displayNumberArea: [],
    tags: [],
    departments: []
  }

  private limitArr: any[] = [] // 权限控制

  private pagingData: any = { total: 0, limit: 10, page: 1 }

  private showLoading = false

  private query: any = {}

  private currentData: any = {}

  private isShowDrawer = false

  private advanceQuery: any = []

  private isShowTabel = false

  private stateOptions: object[] = [
    { name: '呼入', _id: 'incoming' },
    { name: '外呼', _id: 'dialout' },
    { name: '转移', _id: 'transfer' },
    { name: '咨询转移', _id: 'consultTransfer' },
    { name: '双向回呼', _id: 'webcall' },
    { name: '预览外呼', _id: 'previewDialout' },
    { name: '自动外呼', _id: 'autoDialout' }
  ]

  private quickSearchForm = { // 快捷检索数据（时间条件，类型）
    form: {
      customerOrAgentName: '',
      callType: [],
      time: [ // 创建时间 默认显示最近七天
        getFormatDateTime(new Date(new Date().getTime() - 3600 * 1000 * 24 * 6), '').split(' ')[0] + ' 00:00:00',
        getFormatDateTime(new Date(), '').split(' ')[0] + ' 23:59:59'
      ]
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '快捷检索', inputType: 'input', placeholder: '客户号码或座席名称', name: 'customerOrAgentName', clearable: true },
      { label: '呼叫类型', inputType: 'select', clearable: true, selectData: this.stateOptions, name: 'callType', multiple: true },
      { label: '呼叫时间', inputType: 'dateTimeRange', clearable: true, name: 'time' }
    ]
  }

  private pickerOptions: any = {
    shortcuts: [{
      text: '最近一周',
      onClick (picker: any) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 6)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }, {
      text: '最近一个月',
      onClick (picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 29)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }, {
      text: '最近三个月',
      onClick (picker) {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 89)
        const startTime = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 0, 0, 0)
        const endTime = new Date(end.getFullYear(), end.getMonth(), end.getDate(), 23, 59, 59)
        picker.$emit('pick', [startTime, endTime])
      }
    }]
  }

  private tableHeaders = [
    {
      label: '客户号码',
      prop: 'customerNumber',
      width: 150
    },
    {
      label: '座席名称',
      prop: 'agentName',
      width: 100
    },
    {
      label: '呼叫类型',
      prop: 'callType',
      width: 100
    },
    {
      label: '呼叫状态',
      prop: 'status',
      width: 100
    },
    {
      label: '呼叫时间',
      prop: 'startTime',
      width: 140
    },
    {
      label: '通话时长', // 通话结束时间 - 呼叫时间
      prop: 'bridgeDuration'
    },
    {
      label: '通话录音',
      prop: 'recordFileUrl',
      width: 120
    },
    {
      label: '留言录音',
      prop: 'voiceMailUrl',
      width: 120
    },
    {
      label: '客户地区',
      prop: 'customerCountry',
      show: false
    },
    {
      label: '服务号',
      prop: 'trunkNumber',
      width: 120,
      show: false
    },
    {
      label: '外显号',
      prop: 'displayNumber',
      width: 120,
      show: false
    },
    {
      label: '外显号地区',
      prop: 'displayNumberArea',
      show: false
    },
    {
      label: '虚拟号',
      prop: 'virtualNumber',
      show: false,
      width: 120
    },
    {
      label: '座席工号',
      prop: 'agentNumber',
      width: 100,
      show: false
    },
    {
      label: '技能组',
      prop: 'queueName',
      width: 120,
      show: false
    },
    {
      label: '语音导航',
      prop: 'ivrName',
      show: false
    },
    {
      label: '座席振铃时长', // 座席接听应答时间 - 呼叫时间
      prop: 'agentRingDuration',
      sortable: true,
      width: 120,
      show: false
    },
    {
      label: '座席接听时间', // 座席接听应答时间 - 呼叫时间
      prop: 'agentAnswerTime',
      sortable: true,
      width: 140,
      show: false
    },
    {
      label: '呼叫座席时间', // 座席接听应答时间 - 呼叫时间
      prop: 'agentStartTime',
      sortable: true,
      width: 140,
      show: false
    },
    {
      label: '客户振铃时长', // 客户接听应答时间 - 呼叫时间
      prop: 'customerRingDuration',
      sortable: true,
      width: 120,
      show: false
    },
    {
      label: '客户接听时间',
      prop: 'customerAnswerTime',
      width: 140,
      show: false
    },
    {
      label: '挂机方',
      prop: 'hangUpSide',
      show: false
    },
    {
      label: '呼叫失败原因',
      prop: 'failureReason',
      width: 120,
      show: false
    },
    {
      label: '满意度调查结果',
      prop: 'keys',
      width: 150,
      show: false
    },
    {
      label: '满意度调查时长', // 满意度结束时间 - 满意度开始时间
      prop: 'satisfyDuration',
      width: 120,
      show: false
    },
    {
      label: '通话记录ID',
      prop: '_id',
      show: false,
      width: 150
    },
    {
      label: '客户名称',
      prop: 'customerName',
      width: 150
    },
    {
      label: '挂机时间',
      prop: 'hangupTime',
      width: 150
    },
    {
      label: '标签',
      prop: 'tags'
    },
    {
      label: '座席部门',
      prop: 'department',
      width: 140,
      show: false
    },
    {
      label: '转出座席工号',
      prop: 'transferAgent',
      width: 100,
      show: false
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  // 批量操作设置
  private configBatchs = [
    { name: '批量导出记录', action: 'handleExportRecord', tipContent: '单个任务最大支持3,000,000条记录，生成的压缩包30天内有效', _id: 'exportCdr' },
    { name: '批量导出录音', action: 'handleExportSound', tipContent: '1.单个任务最大支持打包10,000条录音，每2500条录音会单独生成一个zip包；2.所选择的录音如过期将不会被导出；3.生成的压缩包30天内有效', _id: 'exportCdrRecord' }
  ]
  // 自定义表头

  private checkHeaders = []
  // list 数据
  private tableData = []

  private currentAction: string = ''

  private checkHeadersChange (checkList, isInit) {
    this.$set(this, 'checkHeaders', checkList)
    if (isInit !== true) {
      this.saveCallTabelHeaders(checkList)
    }
  }

  private changeCustomerRelation (info) {
    this.currentData.customerName = info.custName
    this.currentData.customerNumber = info.phone
  }

  private batchClick (action, selectList) {
    this.tableCheckedList = selectList || []
    this.currentAction = action
    if (action === 'handleExportRecord' || action === 'handleExportSound') {
      this.openExportDialog()
    }
  }

  private openExportDialog () { // 打开导出的弹窗
    const selectList = this.tableCheckedList || []
    let count = 0
    if (typeof selectList === 'object') { // 单个操作
      count = selectList.length || 0
    } else { // 全选
      count = this.pagingData.total || 0
    }
    if (count > 3000000) { // 操作数据大于300W，提示词
      this.$message({ message: '单个任务最大支持3,000,000条记录', type: 'error' })
      return false
    }
    const dialogTitle = this.currentAction === 'handleExportRecord' ? '批量导出记录' : '批量导出录音'
    this.exportDialogRef.setDialogData({ exportDialog: true, count, dialogTitle, currentAction: this.currentAction })
  }

  private dialogSave (data: any) { // 导出弹窗外抛的保存事件
    this.exportDialogRef.setDialogData({ exportDialog: false })
    this.handleExportRecord(data.comment || '', data.exportIvr || false)
  }

  private handleExportRecord (comment: string, exportIvr: boolean) {
    const selectList = this.tableCheckedList
    let sendData = {}
    if (typeof selectList === 'object') { // 单个操作，传ids
      sendData = { ids: selectList || [] }
    } else { // 全选传查询条件
      // 从其他模块设置查询条件
      if (this.forceCondition && Object.keys(this.forceCondition).length > 0) {
        sendData = {
          condition: this.forceCondition
        }
      } else {
        sendData = { condition: this.query }
      }
    }
    let actionData = {}
    // 导出记录ivr，内容不
    if (this.currentAction === 'handleExportRecord') {
      actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page, comment: comment || '', exportIvr: exportIvr || false }, sendData)
    } else {
      actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page, comment: comment || '' }, sendData)
    }
    const actionUrl = this.currentAction === 'handleExportSound' ? '/call/action/export/cdrRecord' : '/call/action/export/cdr'
    IvrModule.IvrCommonAction({ url: actionUrl, method: 'POST', data: actionData }).then(res => {
      if (res && res.success && res.data) {
        this.callTabelRef.cancelSelectFun() // 关闭批量操作栏
        const h = this.$createElement
        this.$message({
          message: h('div', { style: 'color:#2ed47a' }, [
            h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
            h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
            h('span', {}, '查看')
          ]),
          type: 'success',
          duration: 5000
        })
      }
    })
  }

  private jumpToTransmissionCenter () { // 跳转到传输中心
    this.currentAction === 'handleExportSound' ? this.$router.push('/transmission_center/index/tx_export_task?taskModule=cdrRecordFile') : this.$router.push('/transmission_center/index/tx_export_task?taskModule=cdr')
  }

  private handleLimit () {
    let arr: any[] = []
    this.limitArr = []
    if (this.moduleType === 'autoOutCall') { // 自动外呼管理
      arr = ['auto_call_task_list_voice_database_audition', 'auto_call_task_list_voice_database_download', 'auto_call_task_list_callSheet_batch_exportCdrRecord', 'auto_call_task_list_callSheet_batch_exportCdr'] //  试听，下载, 批量导出录音， 批量导出记录
    } else if (this.moduleType === 'myAutoOutCall') { // 我的自动外呼
      arr = ['my_auto_call_task_list_voice_database_audition', 'my_auto_call_task_list_voice_database_download', 'my_auto_call_task_list_callSheet_batch_exportCdrRecord', 'my_auto_call_task_list_callSheet_batch_exportCdr'] //  试听，下载, 批量导出录音， 批量导出记录
    } else if (this.moduleType === 'previewOutCall') { // 预览外呼管理
      arr = ['preview_dialout_list_voice_database_audition', 'preview_dialout_list_voice_database_download', 'preview_dialout_list_callSheet_batch_exportCdrRecord', 'preview_dialout_list_callSheet_batch_exportCdr'] //  试听，下载, 批量导出录音， 批量导出记录
    } else if (this.moduleType === 'myPreviewOutCall') { // 我的预览外呼
      arr = ['my_call_task_list_voice_database_audition', 'my_call_task_list_voice_database_download', 'my_call_task_list_callSheet_batch_exportCdrRecord', 'my_call_task_list_callSheet_batch_exportCdr'] //  试听，下载, 批量导出录音， 批量导出记录
    } else { // 数据中心
      arr = ['callSheet_audition', 'callSheet_download', 'callSheet_batch_exportCdrRecord', 'callSheet_batch_exportCdr'] //  试听，下载, 批量导出录音， 批量导出记录
    }
    arr.forEach((item: string) => {
      if (isHasFuncOrMenus(item, this.$store.state.common.session.user, false)) {
        if (item.indexOf('_exportCdr') > -1) { // 有批量导出记录 || 批量导出录音的权限
          if (item.indexOf('_exportCdrRecord') > -1) {
            this.limitArr.push('exportCdrRecord')
          } else {
            this.limitArr.push('exportCdr')
          }
        }
        if (item.indexOf('_audition') > -1) {
          this.limitArr.push('audition')
        }
        if (item.indexOf('_download') > -1) {
          this.limitArr.push('download')
        }
      }
    })
    this.configBatchs = this.configBatchs.filter(batchItem => this.limitArr.indexOf(batchItem._id) > -1) // 过滤批量操作的权限
  }

  private mounted () {
    this.handleLimit()
    this.getCallTabelHeaders()
    this.getCallList(this.quickSearchForm, 'mounted')
    this.$getCache('/call/action/general/query', ['phoneSatisfactionList'], false)
    this.$bus.$on('changeTagData', (data, cdrId) => {
      this.tableData.forEach(item => {
        if ((item as any)._id === cdrId) {
          Vue.set(item, 'tags', data)
        }
      })
    })
    this.$getCache('/call/action/general/query', ['phoneSatisfactionList'], false).then(() => {
      this.getCallList(this.quickSearchForm, 'mounted')
    })
  }

  private created () {
    TagModule.getTagTree().then(res => {
      this.fieldSelectList.tags = TagModule.tagAllTree
    })
    const actionData = {
      url: '/base/action/department/query',
      method: 'post',
      data: {}
    }
    organizationConfigModule.organizationCommonAction(actionData).then(res => {
      if (res && res.success && res.data) {
        this.fieldSelectList.departments = res.data.tree || []
      }
    })
  }

  get tagMap () {
    return TagModule.tagMap
  }

  private dialoutClick (phoneNum, extraNumber) {
    if (this.isCustom) {
      this.$emit('dialout', phoneNum)
      return
    }
    CtiModule.CtiDialoutAction({ calleeNumber: phoneNum, extraNumber }).then((res: any) => {
      if (res && res.success) {
        this.$message({ message: '外呼成功', type: 'success' })
      }
    })
  }

  private handelList (resData) {
    resData.forEach((item: any) => {
      if (item.keys) {
        const satisArr = this.getPhoneSatisfactionList || []
        let str = ''
        satisArr.forEach((item1) => {
          if (item.keys.indexOf(item1.key) > -1) {
            str += item1.value
          }
        })
        if (!str) {
          str = '--'
        }
        item.keysName = str
      }
    })
    return resData
  }

  private getConditionList (): void {
    const data = { url: '/call/action/cdr/quickQuery/list', method: 'GET' }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success && res.data) {
        this.customList = this.deaultCustomList.concat(res.data.list || [])
      }
    })
  }

  private saveConditionFun (obj: any) {
    const queryObj: any = { name: obj.name, advanceQuery: obj.advanceQuery }
    if (obj.currentCustomId) {
      queryObj._id = obj.currentCustomId
    }
    const data = { url: '/call/action/cdr/quickQuery/save', method: 'POST', data: queryObj }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success) {
        this.getConditionList()
      }
    })
  }

  private popverShow () {
    this.getConditionList()
  }

  private deleteCustomClick (item) {
    const queryObj: any = { _id: item._id }
    const data = { url: '/call/action/cdr/quickQuery/delete ', method: 'POST', data: queryObj }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success) {
        this.getConditionList()
      }
    })
  }

  private getCallDataList (source = '') {
    this.showLoading = true
    if (source === 'custom') {
      this.query = {}
      if (this.advanceQuery && this.advanceQuery.length > 0) {
        this.query.advanceQuery = this.advanceQuery
      } else {
        delete this.query.advanceQuery
      }
    };

    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.query, this.forceCondition || {})
    const data = { url: '/call/action/cdr/list', method: 'POST', hideLoading: true, data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      this.$bus.$emit('restAudioStatus') // 查询的时候，把当前启动的录音重置
      if (res.success && res.data) {
        const resData = this.handelList(res.data.list || [])
        this.tableData = resData || []
        this.pagingData.total = res.data.count || 0
      }
      this.showLoading = false
    })
  }

  public pageChange (page) {
    this.pagingData.page = page
    this.getCallDataList()
  }

  private pageSizeChange (size) {
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.getCallDataList()
  }

  private restTablePlay (id: string, currentPlay: boolean) { // 点击列表的听取录音，重置其他数据
    this.tableData.forEach((item: any) => {
      if (item._id === id) {
        item.isPlay = currentPlay
      } else {
        item.isPlay = false
      }
    })
  }

  private handleDetail (item) {
    this.$set(this, 'currentData', item)
    this.isShowDrawer = true
    this.$nextTick(() => {
      (this as any).$refs.callSummaryRef.updateSummaryData({ callSheetId: item._id, phone: item.customerNumber, cdr: item })
    })
  }

  private getCallList (form, type) {
    this.pagingData.page = 1
    this.$nextTick(() => {
      if (!type) {
        this.callTabelRef.clearSelection()
      }
    })
    this.query = {}
    if (form.form) {
      Object.keys(form.form).forEach((key) => {
        if (key === 'time') {
          if (form.form[key] && form.form[key].length > 0) {
            this.query.startTime1 = form.form[key][0]
            this.query.startTime2 = form.form[key][1]
          }
        } else {
          if (form.form[key] && form.form[key].length > 0) {
            this.query[key] = form.form[key]
          }
        }
      })
    }
    this.getCallDataList('quick')
  }

  private handleSearch (advanceQuery) {
    this.pagingData.page = 1

    for (const i of advanceQuery) {
      if (i.fieldKey === 'tags' && (i.fieldOperator === 'eq' || i.fieldOperator === 'neq')) {
        i.fieldValue[0] = i.fieldValue[0].flat(2)
      }
    }
    this.advanceQuery = advanceQuery;
    (this.$refs as any).customSearch.hide()
    this.getCallDataList('custom')
  }

  private deactivated () {
    this.isShowDrawer = false
  }

  get getPhoneSatisfactionList () {
    return this.$store.state.common.publicCache.phoneSatisfactionList || []
  }

  private getCallTabelHeaders () {
    this.showLoading = true
    const data = { url: '/call/action/cdr/query/header', method: 'POST', data: {} }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res.success) {
        if (res.data && res.data.config.length > 0) {
          this.$set(this, 'tableHeaders', res.data.config)
        }
      }
      this.$nextTick(() => {
        this.isShowTabel = true
      })
      this.showLoading = false
    })
  }

  private saveCallTabelHeaders (headers) {
    const data = { url: '/call/action/cdr/update/header', method: 'POST', data: { config: headers } }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      // if (res.success) {
      //   this.$set(this, 'checkHeaders', headers)
      // }
    })
  }

  public handleSetTabelHeight () {
    this.$nextTick(() => {
      (this.$refs as any).callTabelRef.handleSetTabelHeight()
    })
  }
}
</script>

<style lang="stylus" scoped>
.call-continer
  height 100%
  width 100%
  // border 1px solid #fff
  box-sizing border-box
  // box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
.customSearch
  margin-right 10px
.status
  display flex
  align-items center
  .V7_iconfont
    color #FC6B5C
  .enable
    color #3BB76B
.customerNumber
  margin-right 9px
.customerNumber + .V7_iconfont
  color #BEBEC4
  font-size 12px
.oprate-btn
  color $c-main
  margin-right 10px
  cursor pointer
.oprate-btn:hover
  opacity 0.8
.mytips
  height 24px
  line-height 24px
  display inline-block
  border-radius 12px
  font-size 12px
  color #fff
  padding 0 12px
  cursor pointer
  margin-left 10px
  background #ccc
  vertical-align top
.ccc
  color #ccc
  border 1px solid rgb(179, 185, 199)
  height 22px
  line-height 22px
.mytag
  display inline-block
  max-width 100px
</style>
